//
//  ZZUserAccount.swift
//  SinaWeibo
//
//  Created by QUAN on 15/11/11.
//  Copyright © 2015年 QUAN. All rights reserved.
//

import UIKit

class ZZUserAccount: NSObject, NSCoding{

    var access_token: String?
    //生命周期
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expires_date: NSDate?
    //uid
    var uid: String?
    //头像地址
    var avatar_large: String?
    //名字
    var name: String?
    
    //重写
    init(dict: [String: AnyObject]) {
        
        super.init()

        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String{
        
        let keys = ["access_token", "expires_in", "uid", "avatar_large", "name", "expires_date"]
        
        return dictionaryWithValuesForKeys(keys).description
        
    }
    
    //外部调用归档方法
    func saveAccount() {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        print(path)
    }
    
    //外部调用解归档方法
    class func loadAccount() -> ZZUserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZZUserAccount {
            return account
        }
        return nil
        
        
    }

    //解归档方法
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        
    }
    
    //归档方法
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")

    }
}




